const PaymentService = require('../services/paymentService');
const Order = require('../models/Order');
const { validationResult } = require('express-validator');
const { logger } = require('../utils/logger');
const pointsService = require('../services/pointsService');

/**
 * 支付控制器
 * 处理支付相关的API请求
 */
class PaymentController {
  constructor() {
    this.paymentService = new PaymentService();
  }

  /**
   * 创建支付订单
   * POST /api/payments/create
   */
  async createPayment(req, res) {
    try {
      // 验证请求参数
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '请求参数验证失败',
          errors: errors.array()
        });
      }

      const { orderId, paymentMethod } = req.body;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证订单所有者
      if (order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权限访问此订单'
        });
      }

      // 验证订单状态
      if (order.status !== 'pending') {
        return res.status(400).json({
          success: false,
          message: '订单状态不允许支付'
        });
      }

      // 验证支付状态
      if (order.payment_status === 'completed') {
        return res.status(400).json({
          success: false,
          message: '订单已支付完成'
        });
      }

      // 构建支付数据
      const paymentData = {
        method: paymentMethod,
        amount: order.total_amount,
        orderId: order.id,
        orderNumber: order.order_number,
        description: `CU MR BULL 订单支付 - ${order.order_number}`,
        userInfo: {
          id: userId,
          phone: req.user.phone
        }
      };

      // 创建支付订单
      const paymentResult = await this.paymentService.createPayment(paymentData);

      // 更新订单支付方式
      await Order.updatePaymentMethod(orderId, paymentMethod);

      res.json({
        success: true,
        message: '支付订单创建成功',
        data: paymentResult
      });

    } catch (error) {
      logger.error('创建支付订单失败:', error);
      res.status(500).json({
        success: false,
        message: '创建支付订单失败',
        error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
      });
    }
  }

  /**
   * 支付宝支付回调
   * POST /api/payments/alipay/notify
   */
  async alipayNotify(req, res) {
    try {
      logger.info('收到支付宝支付回调');

      // 验证支付宝回调
      const verifyResult = await this.paymentService.verifyPaymentCallback('alipay', req.body);
      
      if (verifyResult.success) {
        // 更新订单支付状态
        const order = await Order.findByOrderNumber(verifyResult.orderNumber);
        if (order) {
          await Order.updatePaymentStatus(order.id, verifyResult.status, {
            transaction_id: verifyResult.transactionId,
            payment_time: new Date(),
            payment_amount: verifyResult.amount
          });

          // 如果支付成功，更新订单状态为已确认
          if (verifyResult.status === 'completed') {
            await Order.updateStatus(order.id, 'confirmed');
            try { await pointsService.awardPointsForOrder(order); } catch (e) { logger.warn('awardPointsForOrder error:', e.message); }
          }
        }

        // 返回支付宝要求的成功响应
        res.send('success');
      } else {
        res.send('fail');
      }

    } catch (error) {
      logger.error('支付宝回调处理失败:', error);
      res.send('fail');
    }
  }

  /**
   * 微信支付回调
   * POST /api/payments/wechat/notify
   */
  async wechatNotify(req, res) {
    try {
      logger.info('收到微信支付回调');

      // 验证微信支付回调
      const verifyResult = await this.paymentService.verifyPaymentCallback('wechat', req.body);
      
      if (verifyResult.success) {
        // 更新订单支付状态
        const order = await Order.findByOrderNumber(verifyResult.orderNumber);
        if (order) {
          await Order.updatePaymentStatus(order.id, verifyResult.status, {
            transaction_id: verifyResult.transactionId,
            payment_time: new Date(),
            payment_amount: verifyResult.amount
          });

          // 如果支付成功，更新订单状态为已确认
          if (verifyResult.status === 'completed') {
            await Order.updateStatus(order.id, 'confirmed');
            try { await pointsService.awardPointsForOrder(order); } catch (e) { logger.warn('awardPointsForOrder error:', e.message); }
          }
        }

        // 返回微信要求的成功响应
        const successXml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        res.set('Content-Type', 'application/xml');
        res.send(successXml);
      } else {
        const failXml = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名验证失败]]></return_msg></xml>';
        res.set('Content-Type', 'application/xml');
        res.send(failXml);
      }

    } catch (error) {
      logger.error('微信支付回调处理失败:', error);
      const failXml = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>';
      res.set('Content-Type', 'application/xml');
      res.send(failXml);
    }
  }

  /**
   * Apple Pay支付验证
   * POST /api/payments/apple-pay/verify
   */
  async applePayVerify(req, res) {
    try {
      const { orderId, paymentToken } = req.body;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证订单所有者
      if (order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权限访问此订单'
        });
      }

      // 这里应该验证Apple Pay的支付令牌
      // 实际项目中需要调用Apple Pay的验证API
      // 已接收 Apple Pay 支付令牌（不在日志中输出敏感内容）
      logger.debug('Apple Pay支付令牌已接收');

      // 模拟支付成功
      await Order.updatePaymentStatus(orderId, 'completed', {
        transaction_id: `apple_pay_${Date.now()}`,
        payment_time: new Date(),
        payment_amount: order.total_amount
      });

      await Order.updateStatus(orderId, 'confirmed');

      res.json({
        success: true,
        message: 'Apple Pay支付验证成功',
        data: {
          orderId: orderId,
          orderNumber: order.order_number,
          status: 'completed'
        }
      });

    } catch (error) {
      logger.error('Apple Pay支付验证失败:', error);
      res.status(500).json({
        success: false,
        message: 'Apple Pay支付验证失败'
      });
    }
  }

  /**
   * Google Pay支付验证
   * POST /api/payments/google-pay/verify
   */
  async googlePayVerify(req, res) {
    try {
      const { orderId, paymentToken } = req.body;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证订单所有者
      if (order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权限访问此订单'
        });
      }

      // 这里应该验证Google Pay的支付令牌
      // 实际项目中需要调用Google Pay的验证API
      // 已接收 Google Pay 支付令牌（不在日志中输出敏感内容）
      logger.debug('Google Pay支付令牌已接收');

      // 模拟支付成功
      await Order.updatePaymentStatus(orderId, 'completed', {
        transaction_id: `google_pay_${Date.now()}`,
        payment_time: new Date(),
        payment_amount: order.total_amount
      });

      await Order.updateStatus(orderId, 'confirmed');

      res.json({
        success: true,
        message: 'Google Pay支付验证成功',
        data: {
          orderId: orderId,
          orderNumber: order.order_number,
          status: 'completed'
        }
      });

    } catch (error) {
      logger.error('Google Pay支付验证失败:', error);
      res.status(500).json({
        success: false,
        message: 'Google Pay支付验证失败'
      });
    }
  }

  /**
   * 现金支付确认
   * POST /api/payments/cash/confirm
   */
  async confirmCashPayment(req, res) {
    try {
      const { orderId } = req.body;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证订单所有者或管理员权限
      if (order.user_id !== userId && req.user.role !== 'admin') {
        return res.status(403).json({
          success: false,
          message: '无权限操作此订单'
        });
      }

      // 验证支付方式
      if (order.payment_method !== 'cash') {
        return res.status(400).json({
          success: false,
          message: '订单支付方式不是现金支付'
        });
      }

      // 更新支付状态
      await Order.updatePaymentStatus(orderId, 'completed', {
        transaction_id: `cash_${Date.now()}`,
        payment_time: new Date(),
        payment_amount: order.total_amount
      });

      await Order.updateStatus(orderId, 'confirmed');

      res.json({
        success: true,
        message: '现金支付确认成功',
        data: {
          orderId: orderId,
          orderNumber: order.order_number,
          status: 'completed'
        }
      });

    } catch (error) {
      logger.error('现金支付确认失败:', error);
      res.status(500).json({
        success: false,
        message: '现金支付确认失败'
      });
    }
  }

  /**
   * 刷卡支付确认
   * POST /api/payments/card/confirm
   */
  async confirmCardPayment(req, res) {
    try {
      const { orderId, transactionId } = req.body;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证订单所有者或管理员权限
      if (order.user_id !== userId && req.user.role !== 'admin') {
        return res.status(403).json({
          success: false,
          message: '无权限操作此订单'
        });
      }

      // 验证支付方式
      if (order.payment_method !== 'card') {
        return res.status(400).json({
          success: false,
          message: '订单支付方式不是刷卡支付'
        });
      }

      // 更新支付状态
      await Order.updatePaymentStatus(orderId, 'completed', {
        transaction_id: transactionId || `card_${Date.now()}`,
        payment_time: new Date(),
        payment_amount: order.total_amount
      });

      await Order.updateStatus(orderId, 'confirmed');

      res.json({
        success: true,
        message: '刷卡支付确认成功',
        data: {
          orderId: orderId,
          orderNumber: order.order_number,
          status: 'completed'
        }
      });

    } catch (error) {
      logger.error('刷卡支付确认失败:', error);
      res.status(500).json({
        success: false,
        message: '刷卡支付确认失败'
      });
    }
  }

  /**
   * 查询支付状态
   * GET /api/payments/status/:orderId
   */
  async getPaymentStatus(req, res) {
    try {
      const { orderId } = req.params;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证订单所有者
      if (order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权限访问此订单'
        });
      }

      res.json({
        success: true,
        message: '获取支付状态成功',
        data: {
          orderId: order.id,
          orderNumber: order.order_number,
          paymentMethod: order.payment_method,
          paymentStatus: order.payment_status,
          totalAmount: order.total_amount,
          paymentTime: order.payment_time,
          transactionId: order.transaction_id
        }
      });

    } catch (error) {
      logger.error('查询支付状态失败:', error);
      res.status(500).json({
        success: false,
        message: '查询支付状态失败'
      });
    }
  }

  /**
   * 获取支持的支付方式
   * GET /api/payments/methods
   */
  async getPaymentMethods(req, res) {
    try {
      const paymentMethods = [
        {
          id: 'alipay',
          name: '支付宝',
          icon: 'alipay-icon',
          enabled: !!process.env.ALIPAY_APP_ID,
          description: '使用支付宝安全支付'
        },
        {
          id: 'wechat',
          name: '微信支付',
          icon: 'wechat-icon',
          enabled: !!process.env.WECHAT_APP_ID,
          description: '使用微信安全支付'
        },
        {
          id: 'apple_pay',
          name: 'Apple Pay',
          icon: 'apple-pay-icon',
          enabled: !!process.env.APPLE_PAY_MERCHANT_ID,
          description: '使用Apple Pay快速支付'
        },
        {
          id: 'google_pay',
          name: 'Google Pay',
          icon: 'google-pay-icon',
          enabled: !!process.env.GOOGLE_PAY_MERCHANT_ID,
          description: '使用Google Pay快速支付'
        },
        {
          id: 'cash',
          name: '现金支付',
          icon: 'cash-icon',
          enabled: true,
          description: '到店现金支付'
        },
        {
          id: 'card',
          name: '刷卡支付',
          icon: 'card-icon',
          enabled: true,
          description: '到店刷卡支付'
        }
      ];

      res.json({
        success: true,
        message: '获取支付方式成功',
        data: paymentMethods
      });

    } catch (error) {
      logger.error('获取支付方式失败:', error);
      res.status(500).json({
        success: false,
        message: '获取支付方式失败'
      });
    }
  }
}

module.exports = PaymentController;